﻿using System;
using System.Runtime.InteropServices;
using System.Text;

public class IniHelper
{
    [DllImport("kernel32")]
    private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

    [DllImport("kernel32")]
    private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

    [DllImport("kernel32")]
    private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);

    private string iniFilePath;

    public IniHelper(string path)
    {
        iniFilePath = path;
    }

    public void WriteValue(string section, string key, string value)
    {
        WritePrivateProfileString(section, key, value, iniFilePath);
    }

    public string ReadValue(string section, string key, string defaultValue = "")
    {
        StringBuilder temp = new StringBuilder(255);
        int i = GetPrivateProfileString(section, key, defaultValue, temp, 255, iniFilePath);
        return temp.ToString();
    }

    public string[] ReadSections()
    {
        byte[] buffer = new byte[65536];
        int length = GetPrivateProfileString(null, null, null, buffer, buffer.Length, iniFilePath);

        string sections = Encoding.Default.GetString(buffer, 0, length);
        return sections.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
    }

    public string[] ReadKeys(string section)
    {
        byte[] buffer = new byte[65536];
        int length = GetPrivateProfileString(section, null, null, buffer, buffer.Length, iniFilePath);

        string keys = Encoding.Default.GetString(buffer, 0, length);
        return keys.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
    }
}